package com.ujson.chat.client.handler;

import com.ujson.base.common.task.AsyncTask;
import com.ujson.base.common.utils.LogUtil;
import com.ujson.chat.client.builder.HeartbeatRequestBuilder;
import com.ujson.chat.common.handler.AbstractHandler;
import com.ujson.chat.common.proto.MessageProto;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <h3>ujson-parent</h3>
 * <p>心跳响应处理器</p>
 *
 * @author JerryLiu  a1031757312@gmail.com
 * @version 1.0
 * @date 2021-11-24 22:01
 */
@Slf4j
@Service
@ChannelHandler.Sharable
public class HeartbeatResponseHandler extends AbstractHandler {
    @Autowired
    private HeartbeatRequestBuilder heartbeatRequestBuilder;

    // 客户端心跳请求间隔50秒
    public static final long WRITE_IDLE_GAP = 50;

    @Override
    public MessageProto.MessageType getMessageType() {
        return MessageProto.MessageType.KEEPALIVE_RESPONSE;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LogUtil.info(log, "client heartbeat active.");
        heart(ctx, heartbeatRequestBuilder.build(ctx.channel()));
    }

    private void heart(ChannelHandlerContext ctx, MessageProto.Message message) {
        ctx.channel().eventLoop().schedule(() -> {
            AsyncTask.addTask(() -> {
                LogUtil.info(log, "client send heartbeat msg");
                ctx.channel().writeAndFlush(message);
            });
            heart(ctx, message);
        }, WRITE_IDLE_GAP, TimeUnit.SECONDS);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if (!super.messageTypeCheck(ctx, msg)) {
            return ;
        }
        // startt business handle
        LogUtil.info(log, "heart beat response read");



    }
}
